package com.zhugang.week12;

import java.util.*;

/**
 * @program algorithms
 * @description: threeSum
 * @author: chanzhugang
 * @create: 2022/09/06 19:57
 */
public class ThreeSum {

    /**
     * 15 三数之和
     * 排序 + 缓存
     *
     * @param nums
     * @return
     */
    public List<List<Integer>> threeSum(int[] nums) {
        // i != j && i != k && j != k ,nums[i] + nums[j] + nums[k] == 0
        // 排序 + 缓存
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        int n = nums.length;
        Map<Integer, Integer> cache = new HashMap<>();
        for (int i = 0; i < n; i++) {
            cache.put(nums[i], i);
        }

        for (int i = 0; i < n; i++) {
            if (i != 0 && nums[i - 1] == nums[i]) {
                // 排除重复取的
                continue;
            }
            for (int j = i + 1; j < n; j++) {
                if (j != i + 1 && nums[j - 1] == nums[j]) {
                    continue;
                }
                // 两数和的相反数
                int target = -(nums[i] + nums[j]);
                if (!cache.containsKey(target)) {
                    continue;
                }
                int k = cache.get(target);
                if (k > j) {
                    // 下标满足 i < j < k
                    result.add(Arrays.asList(nums[i], nums[j], nums[k]));
                }
            }
        }
        return result;
    }
}